"""

 LDAP Users import module
 $Id: ldapImport.py 421 2011-06-06 16:35:04Z andre $

"""
from model import *
import ldap

def LDAPConnect():
    c=session.query(cmConfiguration).first()
    print "using %s, dn=%s/%s" % (c.ldap_url, c.admin_dn, c.secret)

    connection = ldap.initialize(c.ldap_url)
    connection.bind_s(c.admin_dn, c.secret)
    return (c, connection)

def syncLDAPUsers(userFilter='*', fullUpdate=True):
    """
    Return a list of cmUsers, from LDAP
    """
    userList=[]

    c,connection=LDAPConnect()

    limitedFilter='(&%s(uid=%s))' % (c.filter, userFilter)
    attrs=map(str, c.attrs)

    print "Searching %s with filter %s" % (attrs, limitedFilter)

    for dn, user in connection.search_s(c.base_dn, ldap.SCOPE_SUBTREE, limitedFilter, attrs):
        domain = session.query(cmDomain).filter(cmDomain.name=='cubeholding.com').first()
        DBuser=userByUid(user[c.login_field][0])
        DBuser=session.query(cmUser).filter(cmUser.username==user[c.login_field][0]).filter(cmUser.domain == domain).first()
        if not DBuser:
            if domain:
                newUser=cmUser(username=user[c.login_field][0],
                        password=None,
                        domain=domain,
                        uid=user[c.uid_field][0],
                        name=user[c.name_field][0],
                        surname=user[c.surname_field][0],
                        external=True)
                session.add(newUser)
        elif fullUpdate:
            if DBuser.domain == domain:
                DBuser.name = user[c.name_field][0]
                DBuser.surname = user[c.surname_field][0]
                DBuser.uid=user[c.uid_field][0]
            else:
                # Log that user moved to another domain
                pass
    session.commit()

def syncLDAPGroups(groupFilter='*', fullUpdate=False):
    """
    Return a list of cmGroups, from LDAP
    """
    c,connection=LDAPConnect()

    limitedFilter='(&%s(cn=%s))' % (c.group_filter, groupFilter)
    attrs=['cn', 'gidNumber', 'memberUid']

    domain = session.query(cmDomain).filter(cmDomain.name=='cubeholding.com').first()

    print limitedFilter
    for dn, group in connection.search_s(c.group_dn, ldap.SCOPE_SUBTREE, limitedFilter, attrs):
        if group.has_key('memberUid') and len(group['memberUid']):
            DBgroup=session.query(cmGroup).filter(cmGroup.groupname == group['cn'][0]).filter(cmGroup.domain == domain).first()
            if not DBgroup:
                DBgroup=cmGroup(group['cn'][0], domain=domain, gid=group['gidNumber'][0])
            parseMembers(group, DBgroup)
            if len(DBgroup.users):
                session.add(DBgroup)
            else:
                session.delete(DBgroup)
    session.commit()


def parseMembers(group, g):
    g.users=[]
    for name in group['memberUid']:
        user=session.query(cmUser).filter(cmUser.username==name).filter(cmUser.domain==g.domain).first()
        if user:
            g.users.append(user)
